package com.sx.manage.service.consumer.util;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sx.common.util.http.HttpPoolManager;
import com.sx.manage.biz.consumer.bank.IMConsumerBankMapBiz;
import com.sx.manage.biz.consumer.info.IMNetworkPersonConsumerBiz;
import com.sx.manage.service.bank.IMBaseConsumerBankMapService;
import com.sx.manage.service.bank.IMConsumerBankMapService;
import com.sx.manage.service.consumer.info.IMConsumerOperationInfoService;
import com.sx.manage.util.WebServiceUtils;
import com.sx.model.constants.MDataStatusType;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.account.MAccountNumStatus;
import com.sx.model.constants.type.bank.MBindCardStatus;
import com.sx.model.constants.type.bank.MOutCardType;
import com.sx.model.constants.type.bank.MUserInfoBankValidate;
import com.sx.model.constants.type.bank.MUsingStatus;
import com.sx.model.manage.mybatis.form.bank.MConsumerBankMapForm;
import com.sx.model.manage.mybatis.vo.company.MCompanyImportConsumerInfoVO;
import com.sx.model.manage.mybatis.vo.consumer.MConsumerBankMapVO;
import com.sx.model.manage.mybatis.vo.consumer.MPersonalConsumerNetworkVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.importerror.MImpExcelErrorVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.util.MsgVO;

/**
 * 用户service帮助类 web端service
 * 
 * @author Administrator
 *
 */
@Service("consumerWebServiceUtil")
public class MConsumerWebServiceUtil {
	// 日志
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "mConsumerBankMapBizImpl")
	private IMConsumerBankMapBiz mConsumerBankMapBizImpl;

	// 用户信息新接口
	@Resource(name = "mNetworkPersonConsumerBizImpl")
	public IMNetworkPersonConsumerBiz mNetworkPersonConsumerBizImpl;

	// 用户银行信息
	@Resource(name = "mBaseConsumerBankMapServiceImpl")
	private IMBaseConsumerBankMapService mBaseConsumerBankMapServiceImpl;

	// 扩展信息
	@Resource(name = "consumerOperationInfoServiceImpl")
	private IMConsumerOperationInfoService consumerOperationInfoServiceImpl;

	// 用户银行关系
	@Resource(name = "consumerBankMapServiceImpl")
	private IMConsumerBankMapService consumerBankMapServiceImpl;

	//
	@Resource(name = "httppoolmanager")
	private HttpPoolManager httpPoolManager;

	@Resource(name = "webServiceUtils")
	private WebServiceUtils webServiceUtils;

	/** 更新用户三要素验证信息 */
	public ResultBooleanVO edit_consumerKey_validate(Long consumer_id, String validateResult) {

		if (StringUtils.isNotBlank(validateResult)) {
			// 解析三要素验证信息
			JSONObject jsonObj = new JSONObject(validateResult);
			try {
				/// 更新用户验证信息
				if ((boolean) jsonObj.get("success")) {
					this.mConsumerBankMapBizImpl.updateKeyValidate(consumer_id, MUserInfoBankValidate.VALIDATE_SUCCESS, validateResult);
				} else {// 验证不通过
					this.mConsumerBankMapBizImpl.updateKeyValidate(consumer_id, MUserInfoBankValidate.VALIDATE_FAILURE, validateResult);
				}
			} catch (Exception ex) {
				log.error("更改三要素验证信息时出错error={}", ex);
				return new ResultBooleanVO(false, null, "更改三要素验证信息时出错");
			}
		} else {
			this.mConsumerBankMapBizImpl.updateKeyValidate(consumer_id, MUserInfoBankValidate.VALIDATE_FAILURE, "验证返回结果为空，请重新验证");
		}
		return new ResultBooleanVO();
	}

	/**
	 * 银行卡信息验证
	 * 
	 * @param consumer_id
	 * @return
	 */
	public ResultBooleanVO artificial_key_validate(Long[] consumer_ids) {
		if (null == consumer_ids) {
			log.debug("artificialKeyValidate 传入的参数为空，返回 ");
			return new ResultBooleanVO("m.parameter.is.null");
		}
		List<MPersonalConsumerNetworkVO> consumerList = mNetworkPersonConsumerBizImpl.get_consumer_byIds(consumer_ids);
		StringBuilder errorStr = new StringBuilder();
		MsgVO notChina = new MsgVO();
		ResultBooleanVO result = null;
		for (MPersonalConsumerNetworkVO consumer : consumerList) {
			if (MSystemConstants.NATIONALITY_CHINA_.equals(consumer.getNationality())) {
				notChina.append(consumer.getConsumer_name());
				continue;
			}
			MConsumerBankMapVO bankMapVO = mBaseConsumerBankMapServiceImpl.query_consumerBankMap_for_manage(consumer.getId(), null);
			// 国籍非空，为中国大陆国籍的不能手工认证
			if (null == bankMapVO || StringUtils.isBlank(bankMapVO.getCard_num())) {
				if (errorStr.length() > 0) {
					errorStr.append(",").append(consumer.getConsumer_name());
				} else {
					errorStr.append(consumer.getConsumer_name());
				}
				continue;
			} else {
				result = this.mConsumerBankMapBizImpl.updateKeyValidate(bankMapVO.getId(), MUserInfoBankValidate.VALIDATE_SUCCESS, "人工三要素验证");
				if (!result.isSuccess()) {
					errorStr.append(result.getMsg());
				}
			}
		}
		StringBuilder returnStr = new StringBuilder();
		if (notChina.getError().length() > 0) {
			returnStr.append(notChina.getError()).append("是中国大陆用户，不能使用特殊鉴权");
		}
		// 有错误的人员就返回
		if (errorStr.length() > 0) {
			returnStr.append(errorStr).append("用户没有默认的出入金卡，不能通过验证。");
		}
		if (returnStr.length() > 0) {
			log.info(returnStr.toString());
			return new ResultBooleanVO(false, null, returnStr.toString());
		}
		// 修改数据库
		log.debug("人工验证三要素完成，返回");
		return new ResultBooleanVO();
	}

	/**
	 * 银行卡信息验证
	 * 
	 * @param consumer_id
	 * @return
	 */
	public ResultBooleanVO artificial_key_validate(Long consumer_id, Long bank_map_id) {
		if (null == consumer_id || null == bank_map_id) {
			log.debug("artificialKeyValidate 传入的参数为空，返回 ");
			return new ResultBooleanVO("m.parameter.is.null");
		}
		MPersonalConsumerNetworkVO consumerVO = mNetworkPersonConsumerBizImpl.get_consumer_byId(consumer_id).getObjVo();
		StringBuilder errorStr = new StringBuilder();
		MsgVO notChina = new MsgVO();
		ResultBooleanVO result = null;
		if (MSystemConstants.NATIONALITY_CHINA_.equals(consumerVO.getNationality())) {
			notChina.append(consumerVO.getConsumer_name()).append("是中国大陆用户，不能使用特殊鉴权");
			return new ResultBooleanVO(false, null, notChina.toString());
		}
		MConsumerBankMapVO bankMapVO = mBaseConsumerBankMapServiceImpl.query_consumer_bank_map_by_id(bank_map_id).getObjVo();
		// 国籍非空，为中国大陆国籍的不能手工认证
		if (null == bankMapVO || StringUtils.isBlank(bankMapVO.getCard_num())) {
			errorStr.append(consumerVO.getConsumer_name()).append("所选银行卡不存在。");
			return new ResultBooleanVO(false, null, errorStr.toString());
		}
		if (MUserInfoBankValidate.VALIDATE_SUCCESS.equals(bankMapVO.getKey_validate())) {
			return new ResultBooleanVO(false, null, "此卡已经鉴权成功，不能重复鉴权");
		}
		result = this.mConsumerBankMapBizImpl.updateKeyValidate(bankMapVO.getId(), MUserInfoBankValidate.VALIDATE_SUCCESS, "人工三要素验证");
		log.debug("人工验证三要素完成consumer_id={}, Long bank_map_id={},msg={}", consumer_id, bank_map_id, result.getMsg());
		return result;
	}

	/** 直通鉴权 **/
	public ResultBooleanVO directAuthentication(Long[] consumer_ids) {
		if (null == consumer_ids) {
			log.debug("直通鉴权 传入的参数为空，返回 ");
			return new ResultBooleanVO("m.parameter.is.null");
		}
		List<MPersonalConsumerNetworkVO> consumerList = mNetworkPersonConsumerBizImpl.get_consumer_byIds(consumer_ids);
		StringBuilder errorStr = new StringBuilder();
		ResultBooleanVO result = null;
		for (MPersonalConsumerNetworkVO consumer : consumerList) {
			MConsumerBankMapVO bankMapVO = mBaseConsumerBankMapServiceImpl.query_consumerBankMap_for_manage(consumer.getId(), null);
			// 银行卡信息为空的不能通过
			if (null == bankMapVO || StringUtils.isBlank(bankMapVO.getCard_num())) {
				if (errorStr.length() > 0) {
					errorStr.append(",").append(consumer.getConsumer_name());
				} else {
					errorStr.append(consumer.getConsumer_name());
				}
			} else if (MUserInfoBankValidate.VALIDATE_SUCCESS.equals(bankMapVO.getKey_validate())) {
				log.info("此卡已经鉴权成功，不能重复鉴权 consumer_id={},card_num={}", consumer.getId(), bankMapVO.getCard_num());
				errorStr.append("此卡已经鉴权成功，不能重复鉴权");
			} else {
				result = this.mConsumerBankMapBizImpl.updateKeyValidate(bankMapVO.getId(), MUserInfoBankValidate.VALIDATE_SUCCESS, "人工三要素验证");
				if (!result.isSuccess()) {
					errorStr.append(result.getMsg());
				}
			}
		}
		// 有错误的人员就返回
		if (errorStr.length() > 0) {
			log.debug(errorStr.toString() + " 用户没有默认的银行卡信息，不能通过验证。");
			return new ResultBooleanVO(false, null, errorStr.toString() + "用户没有默认的出入金卡，不能通过验证。");
		}
		return new ResultBooleanVO();
	}

	/** 直通鉴权 **/
	public ResultBooleanVO directAuthentication(Long consumer_id, Long bank_map_id) {
		if (null == consumer_id || null == bank_map_id) {
			log.debug("直通鉴权 传入的参数为空，返回 ");
			return new ResultBooleanVO("m.parameter.is.null");
		}
		MPersonalConsumerNetworkVO consumerVO = mNetworkPersonConsumerBizImpl.get_consumer_byId(consumer_id).getObjVo();
		StringBuilder errorStr = new StringBuilder();
		ResultBooleanVO result = null;
		MConsumerBankMapVO bankMapVO = mBaseConsumerBankMapServiceImpl.query_consumer_bank_map_by_id(bank_map_id).getObjVo();
		// 银行卡信息为空的不能通过
		if (null == bankMapVO || StringUtils.isBlank(bankMapVO.getCard_num())) {
			errorStr.append(consumerVO.getConsumer_name()).append("用户没有默认的银行卡信息，不能通过验证。");
			log.debug(errorStr.toString());
			return new ResultBooleanVO(false, null, errorStr.toString());
		}
		if (MUserInfoBankValidate.VALIDATE_SUCCESS.equals(bankMapVO.getKey_validate())) {
			return new ResultBooleanVO(false, null, "此卡已经鉴权成功，不能重复鉴权");
		}
		result = this.mConsumerBankMapBizImpl.updateKeyValidate(bankMapVO.getId(), MUserInfoBankValidate.VALIDATE_SUCCESS, "人工三要素验证");
		log.debug("直通鉴权 完成consumer_id={}, Long bank_map_id={},msg={}", consumer_id, bank_map_id, result.getMsg());
		return result;
	}

	// 绑出金卡前的验证
	public ResultBooleanVO bindBankOutCardValidate(Long consumer_id, MOutCardType outCardType, Long bank_map_id) {
		MConsumerBankMapVO bankMapVO = mBaseConsumerBankMapServiceImpl.query_consumer_bank_map_by_id(bank_map_id).getObjVo();
		if (null == bankMapVO || null == bankMapVO.getId()) {
			return new ResultBooleanVO(false, null, "所选银行卡不存在");
		}
		//
		log.info("绑定的出入金卡前用户信息验证，consumer_id={},bank_map_id={}", consumer_id, bank_map_id);
		// 判断是否已经进行了三要素要争
		if (MUserInfoBankValidate.VALIDATE_FAILURE.equals(bankMapVO.getKey_validate())) {
			log.info("绑定的出入金卡三要素验证失败，不能绑定consumer_id={},bank_map_id={}", consumer_id, bank_map_id);
			return new ResultBooleanVO(false, null, "绑定的出金卡信息鉴权失败，不能绑定");
		} else if (MUserInfoBankValidate.VALIDATE_NOT_YET.equals(bankMapVO.getKey_validate())) {
			log.info("绑定的出入金卡没有进行三要素验证，不能绑定consumer_id={},bank_map_id={}", consumer_id, bank_map_id);
			return new ResultBooleanVO(false, null, "绑定的出金卡没有进行信息鉴权，不能绑定");
		}
		// 出入金只能是主卡
		if (null != bankMapVO.getOut_card_type()) {
			log.info("绑定的出金卡已经绑定出金卡类型bank_map_id={}, Out_card_type={}", bank_map_id, bankMapVO.getOut_card_type());
			return new ResultBooleanVO(false, null, "绑定的出金卡已经绑定其它类型");
		} // 绑定的是主卡
		MConsumerBankMapForm bankMapForm = new MConsumerBankMapForm();
		bankMapForm.setConsumer_id(consumer_id);
		bankMapForm.setChannel_status(MDataStatusType.DATA_AVAILABLE);
		List<MConsumerBankMapVO> bankMapList = mBaseConsumerBankMapServiceImpl.query_consumer_bank_list(bankMapForm).getData();
		for (MConsumerBankMapVO bankMapVOValidate : bankMapList) {
			if (outCardType.equals(bankMapVOValidate.getOut_card_type())) {
				log.info("用户consumer_id={},card={},已经绑定 outCardType={},不能重复绑定", consumer_id, bankMapVOValidate.getCard_num(), outCardType);
				return new ResultBooleanVO(false, null, "用户已经有其它银行卡绑定此出金卡类型");
			}
		}
		// 没有默认的主卡，返回true
		return new ResultBooleanVO();
	}

	/** 解绑出金卡 **/
	public ResultBooleanVO relieveBankOutCard(Long consumer_id, MConsumerBankMapVO bankMapVO, MConsumerLoginVO loginVO) {
		if (null == bankMapVO.getOut_card_type()) {
			log.info("银行卡数据异常，出金类型为空bankMapVO={}", bankMapVO);
			return new ResultBooleanVO(false, null, "银行卡数据异常，出金类型为空");
		}
		// // 解除出金卡
		ResultBooleanVO result = relieveBankOutCardOper(consumer_id, bankMapVO);
		if (!result.isSuccess()) {
			log.info(" 解绑失败consumer_id={},error={}", consumer_id, result.getMsg());
			return result;
		}

		// 扩展信息入库
		log.info("解绑成功信息入库consumer_id={}", consumer_id);
		 result = consumerOperationInfoServiceImpl.updateOutCardStatus(consumer_id, bankMapVO.getOut_card_type(), MBindCardStatus.RELIEVE);
		if (!result.isSuccess()) {
			return result;
		}
		log.info("解绑成功修改银行卡信息consumer_id={},bank_map_id={}", bankMapVO.getId());
		// 修改银行卡的状态
		result = relieveOutCardBindSuccess(bankMapVO);
		if (!result.isSuccess()) {
			log.info("修改银行卡信息失败error={}", result.getMsg());
			return result;
		}
//		// 解绑出入金卡(电子账户与出入卡的关系不在这里，是单独维护的，而且现在，解绑是用户自己来做)
//		log.info("电子账户解绑银行卡consumer_id={}", consumer_id);
//		ResultBooleanVO resultBoolean = elecAccountBizImpl.relieveCardNum(consumer_id, loginVO);
//		if (!resultBoolean.isSuccess()) {
//			resultBoolean.setMsg("绑定银行卡失败，请重新绑定");
//			return resultBoolean;
//		}
		return result;
	}

	// 解绑出金卡操作
	@SuppressWarnings("rawtypes")
	public ResultBooleanVO relieveBankOutCardOper(Long consumer_id, MConsumerBankMapVO bankMapVO) {
		log.info("解绑用户银行卡consumer_id={},bank_map_id={}", consumer_id, bankMapVO.getId());
		// 获取用户、银行信息
		MPersonalConsumerNetworkVO consumerVO = mNetworkPersonConsumerBizImpl.get_consumer_byId(consumer_id).getObjVo();
		// 生成解绑出入金form
//		BindBankCardForm cardForm = ClassPackUtil.createRelieveOutBankCardForm(consumerVO, bankMapVO, webServiceUtils.queryBranchAccountNo(consumer_id), webServiceUtils.queryTradeMemberCode(consumer_id));
		try {
//			HttpResult httpResult = httpPoolManager.getHttpClient().postAuthorization(WebServiceUtil.bindBankOutCardUrl(), ContentType.JSON, null, MConsumerWebServiceImpl.HTTP_TIME_OUT, JackJsonUtil.objToJson(cardForm), "UTF-8");
//			if (null != httpResult && 200 == httpResult.getStatus()) {
//				log.info("解绑出入金结果 httpResult={}", httpResult.getHttpresult());
//				B2BQueryAccountRssultVO accountResult = JackJsonUtil.jsonToJavaBean(httpResult.getHttpresult(), B2BQueryAccountRssultVO.class);
//				// 返回绑定关系不存在时，认定成功，这样就能继续资源，删除绑定信息的操作
//				if (!accountResult.isSuccess() && !MSystemConstants.HX_RELIEVE_RETURN_FALSE_PASS.equals(accountResult.getMsgcode())) {
//					log.info("解绑失败error={}", accountResult.getMsg());
//					return new ResultBooleanVO(false, "sx.consumer.bank.relieve.bank.out.card.fail", accountResult.getMsg());
//				} else {
//					return new ResultBooleanVO();
//				}
//			}
		} catch (Exception e) {
			log.error("解绑出金账户http异常error={}", e);
		}
		return new ResultBooleanVO("sx.consumer.bank.relieve.bank.out.card.fail");
	}

	/** 解绑成功后续操作 **/
	private ResultBooleanVO relieveOutCardBindSuccess(MConsumerBankMapVO bankMapVO) {
		log.info("解绑成功修改银行卡信息consumer_id={},bank_map_id={}", bankMapVO.getId());
		// 查询银行信息
		MConsumerBankMapForm bankMapForm = new MConsumerBankMapForm();
		bankMapForm.setId(bankMapVO.getId());
		bankMapForm.setAccount_no(null);
		bankMapForm.setBank_account_no(null);
		bankMapForm.setAccount_no_status(MAccountNumStatus.NOT_OPEN);
		bankMapForm.setTrade_mem_code(null);
		bankMapForm.setStatus(MUsingStatus.CAN_USED);
		bankMapForm.setChannel_status(MDataStatusType.DATA_AVAILABLE);
		bankMapForm.setBank_account_no(null);
		bankMapForm.setOut_card_type(null);
		// 修改银行信息
		return consumerBankMapServiceImpl.consumerBankMapUpdateForNull(bankMapForm);
	}

	/** 导入个人用户入库前的验证，解绑出金卡等操作 */
	public ResultBooleanVO excelImportRelieveBank(MPersonalConsumerNetworkVO networkVO, MCompanyImportConsumerInfoVO importConsumer, MConsumerLoginVO loginVO) {
		log.info("导入个人用户入库前的验证，解绑出金卡等操作consumer_id={},importConsumer={}", networkVO.getId(), importConsumer);
		// 获取用户在用的卡，全部解绑
		List<MConsumerBankMapVO> bankMapList = this.mBaseConsumerBankMapServiceImpl.queryBankListByConsumerId(networkVO.getId()).getData();
		ResultBooleanVO result = null;
		MImpExcelErrorVO errorVO = new MImpExcelErrorVO();
		if (null != bankMapList) {
			for (MConsumerBankMapVO bankMapVO : bankMapList) {
				errorVO.setUser_name(bankMapVO.getBank_consumer_name());
				if (null != bankMapVO.getOut_card_type()) {
					if (!importConsumer.getCard_num().equals(bankMapVO.getCard_num())) {
						log.info("解绑用户银行卡bankMapVO={}", bankMapVO);
						result = this.relieveBankOutCard(bankMapVO.getConsumer_id(), bankMapVO, loginVO);
						if (!result.isSuccess()) {
							errorVO.appError(result.getMsg());
						}
					}
				}
			}
		}
		if (errorVO.getError().length() > 0) {
			return new ResultBooleanVO(false, null, errorVO.getError().toString());
		}
		return new ResultBooleanVO();
	}

	/** 导入个人用户入库前的验证，解绑出金卡等操作 */
	public MImpExcelErrorVO excelImportRelieveBank(Long consumer_id, MConsumerLoginVO loginVO) {
		log.info("导入个人用户入库前的验证，解绑出金卡等操作consumer_id={}", consumer_id);
		// 获取用户在用的卡，全部解绑
		List<MConsumerBankMapVO> bankMapList = this.mBaseConsumerBankMapServiceImpl.queryBankListByConsumerId(consumer_id).getData();
		ResultBooleanVO result = null;
		MImpExcelErrorVO errorVO = new MImpExcelErrorVO();
		if (null != bankMapList) {
			for (MConsumerBankMapVO bankMapVO : bankMapList) {
				errorVO.setUser_name(bankMapVO.getBank_consumer_name());
				if (null != bankMapVO.getOut_card_type()) {
					log.info("解绑用户银行卡bankMapVO={}", bankMapVO);
					result = this.relieveBankOutCard(bankMapVO.getConsumer_id(), bankMapVO, loginVO);
					if (!result.isSuccess()) {
						errorVO.appError(result.getMsg());
					}
				}
			}
		}
		return errorVO;
	}
}
